<template>
  <div class="upload-list">
    <div class="demo-upload-list" v-for="(item,index) in uploadList">
      <template class="flex">
        <img :src="item.path"/>
        <div class="demo-upload-list-cover" v-if="item.status == 'success'">
          <Icon type="ios-eye-outline" @click.native="handleView(item.path)"></Icon>
          <Icon type="ios-trash-outline" @click.native="handleRemove(item,index)"></Icon>
        </div>
        <cusProgress ref="cusProgress" :status="item.status" width="90px"></cusProgress>
      </template>
    </div>

    <Poptip v-model="visible" placement="right" width="400" :transfer="true">
      <cus-upload v-if="uploadList.length < maxCount" :maxSize="maxSize" :accept="accept"
                  @onBeforeUpload="onBeforeUpload">
        <div class="upload-img">
          <Icon type="ios-add" size="30"/>
          <div class="upload-img-label">上传图片</div>
        </div>
      </cus-upload>

      <div slot="content"
           style="width: 350px;display: flex;flex-direction: column;justify-content: center;align-items: center"
           v-if="option.img">
        <div style="width: 300px;height: 300px;">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :autoCrop="option.autoCrop"
            :canMoveBox="true"
            :centerBox="true"
            :autoCropWidth="300"
            :autoCropHeight="300"
            :enlarge="1.5"
            :mode="option.mode"
          ></vueCropper>
        </div>
        <cus-button style="margin-top: 15px;margin-bottom: 10px;" size="small" @onClick="beginCrop">裁剪并上传</cus-button>
      </div>
    </Poptip>
  </div>
</template>

<script>
  /**
   * @value [{path: '图片路径', status: '图片状态'}]  loading: 上传中, success: 上传成功, wrong: 上传失败
   * @keyLabel      上传文件字段
   * @params        上传文件额外属性
   * @fnc           上传文件方法
   * @deleteFnc     图片删除方法
   * @syncDelete    是否同步删除图片
   * @maxCount      最大可上传数量
   *
   * @onClear 清除暂缓区图片
   */
  import { uploadCropIMG, deleteIMG } from '@/api/organ/business'
  import { VueCropper } from 'vue-cropper'

  export default {
    name: 'cus-uploadIMG',
    components: { VueCropper },
    data () {
      return {
        uploadList: [],
        deleteList: [],
        visible: false,
        option: {
          img: '',
          size: 1,
          outputType: 'png',
          autoCrop: true,
          original: false,
          mode: 'contain',
        }
      }
    },
    props: {
      value: {
        type: Array,
        default: () => {
          return []
        }
      },
      needCrop: {
        type: Boolean,
        default: false,
      },
      keyLabel: {
        type: String,
        default: 'file'
      },
      maxSize: {
        type: Number,
        default: 1024
      },
      accept: {
        type: String,
        default: 'image/*'
      },
      params: {
        type: Object,
        default: () => {
          return {}
        }
      },
      syncDelete: {
        type: Boolean,
        default: true
      },
      fnc: {
        type: Function,
        default: uploadCropIMG
      },
      deleteFnc: {
        type: Function,
        default: deleteIMG
      },
      maxCount: {
        type: [String, Number],
        default: 1
      },
      returnLabel: {
        type: String,
        default: 'data'
      }
    },
    watch: {
      value (newV) {
        this.uploadList = newV
      }
    },
    methods: {
      // 开始截图
      beginCrop () {
        this.$refs.cropper.startCrop()

        this.$refs.cropper.getCropData(data => {

          function getImgSize (base64url) {
            //获取base64图片大小，返回KB数字
            let str = base64url.replace('data:image/png:base64,', '')//这里根据自己上传图片的格式进行相应修改
            let strLength = str.length
            let fileLength = parseInt(strLength - (strLength / 8) * 2)

            // 由字节转换为KB
            let size = ''
            size = (fileLength / 1024).toFixed(2)

            return parseInt(size)
          }

          if (getImgSize(data) > this.maxSize) return this.$Message.error(`最大不能超过${this.maxSize}KB`)

          // do something
          let upload = { path: data, status: 'active' }
          console.log(data)

          this.uploadList.push(upload)
          this.option.img = ''
          this.visible = false
          this.upload(data, upload)
        })
      },
      handleView (path) {
        this.$cu.previewImage(path)
      },
      handleRemove (item, index) {
        if (item.status === 'loading') return this.$Message.wrong('当前图片正在上传中,不可删除')
        this.$cu.dialog({ content: '确认删除改图片?' }).then(() => {
          if (this.syncDelete) {
            this.deleteFncApi(item, index)
          } else {
            // 记录当前被删除数据
            this.deleteList.push(item)
            this.uploadList.splice(index, 1)
          }
          this.option.img = ''
        })
      },
      // 清除暂缓区图片
      onClear () {
        return new Promise((resolve) => {
          let promise = []
          for (let i = 0; i < this.deleteList.length; i++) {
            promise.push(this.deleteFncApi(this.deleteList[i], null))
          }
          Promise.all(promise).then(() => {
            this.deleteList = []
            resolve()
          })
        })
      },
      onBeforeUpload (file) {
        this.option.img = window.URL.createObjectURL(file)
        this.visible = true
      },
      // 图片上传接口
      upload (file, upload) {
        let params = Object.assign({ file: file.replace('data:image/png;base64,', '') }, this.params)

        // data:image/png;base64,
        this.fnc(params).then(res => {
          if (res.code === 1) {
            upload.status = 'success'
            upload.path = res[this.returnLabel]
            this.$Message.success('文件上传成功')
          } else {
            upload.status = 'wrong'
          }
          this.uploadList = this.uploadList.filter(v => v.status === 'success')
          this.$emit('update:value', this.uploadList)
        }).catch(() => {
          upload.status = 'wrong'
          this.uploadList = this.uploadList.filter(v => v.status === 'success')
          this.$emit('update:value', this.uploadList)
        })
      },
      // 图片上传接口
      deleteFncApi (item, index) {
        return new Promise((resolve, reject) => {
          this.deleteFnc({ url: item.path }).then((res) => {
            if (res.code === 1) {
              resolve()
              if (index === 0 || index) {
                this.$Message.success('文件删除成功')
                this.uploadList.splice(index, 1)
              }
            } else {
              reject()
            }
          })
        })
      }
    }
  }
</script>

<style scoped lang="less">
  .upload-list {
    display: flex;
    align-items: center;
    /*padding-bottom: 25px;*/
  }

  .demo-upload-list {
    width: 104px;
    height: 104px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: none;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, .6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: flex;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .upload-img {
    border: 1px dashed #dcdee2;
    border-radius: 4px;
    text-align: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color .2s ease;
    width: 104px;
    height: 104px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    background: rgba(0, 0, 0, 0.04);

    &-label {
      margin-top: 10px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.65);
      line-height: 22px;
    }
  }

  .upload-img:hover {
    border: 1px dashed #2d8cf0;
  }
</style>
